package com.ytjj.qmyx.admin.service.impl;

import com.ytjj.common.exception.ApiException;
import com.ytjj.qmyx.admin.dao.MessageDao;
import com.ytjj.qmyx.admin.dao.MessageTelDao;
import com.ytjj.qmyx.admin.model.response.MessageResponse;
import com.ytjj.qmyx.admin.service.MessageService;
import com.ytjj.qmyx.mall.model.Message;
import com.ytjj.qmyx.mall.model.MessageTel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 *
 *
 * @Version: 1.0
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

	@Resource
	private MessageDao messageDao;

	@Resource
	private MessageTelDao messageTelDao;

	@Override
	public void insertMessage(MessageResponse message) {
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = fmt.parse(message.getRecordTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		message.setSendTime(date);
		Integer nowCount = messageTelDao.getTelCount(message.getOperatorType());
		if(message.getSendUserNum() > nowCount) {
			throw new ApiException("当前可发送用户数为" + nowCount + ", 请重新输入需要发送的用户数！");
		}
		messageDao.insertMessage(message);

		//todo 测试发送cmpp2.0协议短信
//		String[] phones = {"18873058010", "15913953648", "13058034643", "18665837620", "15302629093"};
//		boolean result = SMProxyTools.sendMsg(phones, "【 XXXX优品】你好，我是测试短信");
//		log.info("===cmpp发送结果===={}", result);

		// 当前短信编码 msgNo todo 先注释了
		Integer msgNo = message.getId();

		// 当前需要发送该短信的手机号
		List<MessageTel> operMsgList = messageTelDao.getOperMsgList(message.getOperatorType(), message.getSendUserNum());

		// 发送短信的手机号，状态->待发送 短信编码->msgNo
		if(!CollectionUtils.isEmpty(operMsgList)) {
			for(MessageTel msg : operMsgList) {
				if(msg != null) {
					messageTelDao.updateStatus(msg.getTel(), msgNo.toString());
				}
			}
		}
	}

	@Override
	public List<Message> selectList() {
		return messageDao.selectList();
	}
}
